package net.lulihu.pangolin.headless.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.UUID;

/**
 * 获取cpu信息工具类
 */
@Slf4j
public class NativeKit {

    // 缓存序列号，不需要每次都去获取
    private static String serialNumber = null;

    /**
     * 获取当前操作系统名称. return 操作系统名称 例如:windows linux 等.
     */
    private static String getOSName() {
        return System.getProperty("os.name").toLowerCase();
    }

    /**
     * 判断是否是windows操作系统
     */
    public static boolean isWinOs() {
        return getOSName().contains("windows");
    }

    /**
     * 获取windows 的cpu序列号
     */
    private static String getWindows() {
        try {
            Process process = Runtime.getRuntime().exec(
                    new String[]{"wmic", "cpu", "get", "ProcessorId"});
            process.getOutputStream().close();
            Scanner sc = new Scanner(process.getInputStream());
            sc.next();
            return sc.next();
        } catch (IOException e) {
            throw new RuntimeException("获取CPU序列号异常:", e);
        }
    }

    /**
     * 获取linux 的cpu序列号
     */
    private static String getLinux() {
        BufferedReader bufferedReader;
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"sh", "-c", "dmidecode"});
            bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 寻找标示字符串[hwaddr]
                int index = line.toLowerCase().indexOf("uuid");
                if (index >= 0) {
                    // 取出mac地址并去除2边空格
                    String result = line.substring(index + "uuid".length() + 1).trim();
                    return result.trim();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("获取cpu信息错误", e);
        }
        throw new RuntimeException("获取cpu信息错误");
    }

    /**
     * 获取cpu序列号
     */
    public static String CPUSerialNumber() {
        if (serialNumber == null || serialNumber.length() == 0) {
            try {
                String os = getOSName();
                if (os.contains("windows")) {
                    return serialNumber = getWindows();
                } else if (os.contains("linux")) {
                    return serialNumber = getLinux();
                }
            } catch (Exception e) {
                log.warn("未能正确获取到cpu序列号,使用UUID作为序列号返回");
            }
            return serialNumber = UUID.randomUUID().toString();
        }
        return serialNumber;
    }

}
